//
//  BanJiKaoQingView.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/15.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "BanJiKaoQingView.h"
#import "SYRequestAPI+Teach.h"
#import "CJYearMonthSelectedView.h"

@implementation BanJiKaoQingView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        [self initSubView];
    }
    return self;
}
- (void)initSubView{
    _lessenID = @"";
    beginDate = @"";
    endDate = @"";
    pageSize = 30;
    _dataArray = [NSMutableArray new];
    self.backgroundColor = CONTENTBACKCOLOR;
    [self addSubview:self.tableList];
    [_tableList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
        make.top.equalTo(@0);
    }];
    [_tableList headerRefreshBlock:^{
        self->pageIndex = 1;
        [self->_dataArray removeAllObjects];
        [self setKaiShiShiJian];
        [self setJieShuShiJian];
//        [self->_tableList.mj_header beginRefreshing];
        [self getBanJiKaoQingRequest];
    }];
    [_tableList fooderRefreshBlock:^{
        [self->_tableList.mj_footer beginRefreshing];
        
        NSInteger page = self->_dataArray.count/30;
        if (page == 0) {
            page = 2;
        } else {
            page = self->pageIndex+1;
        }
        self->pageIndex = page;
        [self getBanJiKaoQingRequest];
    }];
    [self setKaiShiShiJian];
    [self setJieShuShiJian];
}
- (UITableView *)tableList{
    if (!_tableList) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 0) style:UITableViewStylePlain];
        tableView.delegate  =self;
        tableView.dataSource = self;
        [tableView registerClass:[BanJiKaoQingCell class] forCellReuseIdentifier:@"BanJiKaoQingCell"];
        tableView.backgroundColor = [UIColor clearColor];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _headerView = [[BanJiKaoQingTopView alloc]init];
        _headerView.mainDelegate = self;
        _headerView.frame = CGRectMake(0, 0,self.mainw, 161);
        tableView.tableHeaderView = _headerView;
        _tableList = tableView;
    }
    return _tableList;
}
#pragma mark - 开始日期选择
- (void)kaiShiRiQiSelected{
    [CJYearMonthSelectedView showDatePickerWithTitle:@"选择月份" andTypeOfFrame:CGRectMake(APP_WIDTH-520,APP_HEIGHT/2-150, 300, 300) minDateStr:@"2000-01" resultBlock:^(NSString * _Nonnull selectValue) {
        if ([selectValue isEqualToString:@"全部"]) {
            [MBProgressHUD zr_showError:@"请选择日期"];
            return ;
        }
        if (selectValue.length>0) {
            NSArray *array = [selectValue componentsSeparatedByString:@"-"];
            NSLog(@"输出日期 %@",selectValue);
            [self->_dataArray removeAllObjects];
            self->kaishiNum = [self valueNum:array];
            if (self->jisshuNum>0) {
                if (self->jisshuNum>self->kaishiNum) {
                    self->beginDate = selectValue;
                    self->_headerView.leftButton.bottomLabel.text = self->beginDate;
                    [self->_dataArray removeAllObjects];
                    self->pageIndex = 1;
                    [self getBanJiKaoQingRequest];
                }else{
                     [XSInfoView showInfo:@"结束日期不能早于开始日期" onSubView:self];
                }
            }else{
                self->beginDate = selectValue;
                self->_headerView.leftButton.bottomLabel.text = selectValue;
                [self->_dataArray removeAllObjects];
                self->pageIndex = 1;
                [self getBanJiKaoQingRequest];
            }
        }
    }];
}
- (int)valueNum:(NSArray *)array{
    NSString *num = [NSString stringWithFormat:@"%@%@",array[0],array[1]];
    int nu = [num intValue];
    return nu;
}
#pragma mark - 结束日期选择
- (void)jieShuRiQiSelected{
    [CJYearMonthSelectedView showDatePickerWithTitle:@"选择月份" andTypeOfFrame:CGRectMake(APP_WIDTH-520,APP_HEIGHT/2-150, 300, 300) minDateStr:@"2000-01" resultBlock:^(NSString * _Nonnull selectValue) {
        if ([selectValue isEqualToString:@"全部"]) {
            [MBProgressHUD zr_showError:@"请选择日期"];
            return ;
        }
        if (selectValue.length>0) {
            NSArray *array = [selectValue componentsSeparatedByString:@"-"];
            NSLog(@"输出日期 %@",selectValue);
            self->jisshuNum = [self valueNum:array];
            if (self->kaishiNum >0) {
                //开始日期有值
                if (self->jisshuNum<self->kaishiNum) {
                    [XSInfoView showInfo:@"结束日期不能早于开始日期" onSubView:self];
                }else{
                    self->jisshuNum = [self valueNum:array];
                    self->beginDate = selectValue;
                    self->_headerView.rightButton.bottomLabel.text = self->beginDate;
                    [self->_dataArray removeAllObjects];
                    [self getBanJiKaoQingRequest];
                }
            }else{
                self->jisshuNum = [self valueNum:array];
                self->endDate = selectValue;
                self->_headerView.rightButton.bottomLabel.text = selectValue;
                [self->_dataArray removeAllObjects];
                [self getBanJiKaoQingRequest];
            }
        }
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BanJiKaoQingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BanJiKaoQingCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[BanJiKaoQingCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BanJiKaoQingCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row%2 == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        cell.backgroundColor = [UIColorChange colorwithHexString:@"#F8F8F8"];
    }
    cell.index = (int)indexPath.row;
    [cell reloadViewLayout];
    cell.checkButton.tag = 100+(int)indexPath.row;
    [cell.checkButton addTarget:self action:@selector(checkBlock:) forControlEvents:UIControlEventTouchUpInside];

    @try {
        BanJiKaoQingListModel *model = _dataArray[indexPath.row];
    } @catch (NSException *exception) {
    } @finally {
    }
    BanJiKaoQingListModel *model = _dataArray[indexPath.row];
    UILabel *xueHaoLabel = (UILabel *)[cell viewWithTag:20];//学号
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:21];//姓名
    UILabel *genderLabel = (UILabel *)[cell viewWithTag:22];//性别
    UILabel *courseTimesLabel = (UILabel *)[cell viewWithTag:23];//课次
    UILabel *qingJiaLabel = (UILabel *)[cell viewWithTag:24];//请假
    UILabel *kuangKeLabel = (UILabel *)[cell viewWithTag:25];//旷课
    UILabel *chiDaoLabel = (UILabel *)[cell viewWithTag:26];//迟到
    UILabel *zaoTuiLabel = (UILabel *)[cell viewWithTag:27];//早退
    xueHaoLabel.text = model.serial;
    nameLabel.text = model.name;
    if ([model.sex isEqualToString:@"1"]) {
        genderLabel.text = @"男";
    }else if ([model.sex isEqualToString:@"2"]){
        genderLabel.text = @"女";
    }else{
        genderLabel.text = @"未知";
    }
    courseTimesLabel.text = model.lessonTimes;
    qingJiaLabel.text = model.leaveTimes;
    kuangKeLabel.text = model.truantTimes;
    chiDaoLabel.text = model.lateTimes;
    zaoTuiLabel.text = model.outTimes;
    return cell;
}
- (void)checkBlock:(UIButton *)sender{
    BanJiKaoQingListModel *model = _dataArray[sender.tag-100];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"BanJiAddNextViewNotice" object:nil userInfo:@{@"index":[NSString stringWithFormat:@"%d",(int)sender.tag],@"status":@"1",@"Model":model}];
    //
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!_titleView) {
        _titleView = [[SJXQHeaderTitleView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44) andArray:@[@"学号",@"姓名",@"性别",@"课次",@"请假",@"旷课",@"迟到",@"早退",@"详情"]];
        _titleView.backgroundColor = CONTENTBACKCOLOR;
    }
    return _titleView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *mainView = [[UIView alloc]init];
    return mainView;
}
- (void)updateModel{
    [_headerView setTtitleLabelText:_mainModel.className];
    [_headerView setDangQianJinDuLabelText:_mainModel.schedule];
    [_headerView setKeChengLabelText:self.courseName];
    [_headerView setRenKeLaoShiLabelText:self.renKeLaoShiName];
    [_headerView setNianJiLabelText:_mainModel.typeName];
    [_headerView setShangKeShiJianLabelText:_mainModel.openDate];
    [_headerView setKeMuLabelText:_mainModel.statusName];
    [_headerView setZhaoShengRenShuLabelext:[NSString stringWithFormat:@"%@/%@",self.students,_mainModel.maxStudents]];
    [_headerView setJiaoShiLabelText:[NSString stringWithFormat:@"%@-%@",_mainModel.campusName,_mainModel.classroom]];
    _headerView.jieYeShiJianLabel.hidden = YES;
//    [_headerView setJieYeShiJianLabelText:_mainModel.finishedDate];
}
- (void)reloadIndex{
    pageIndex = 1;
    [_dataArray removeAllObjects];
    [self getBanJiKaoQingRequest];
}
#pragma mark - 教学-班级-班级考勤
- (void)getBanJiKaoQingRequest{
    if (_lessenID.length == 0) {
        _lessenID = @"0";
    }
    NSDictionary *parama = @{@"classId":_classID,
                             @"lessonId":_lessenID,
                             @"beginDate":beginDate,
                             @"endDate":endDate,
                             @"pageIndex":[NSString stringWithFormat:@"%ld",(long)pageIndex],
                             @"pageSize":[NSString stringWithFormat:@"%d",pageSize]};
   // NSLog(@"班级考勤参数 %@",parama);
    
        
    [MBProgressHUD mj_hideHUDForView:self.tableList];
    [MBProgressHUD mj_showMessage:nil toView:self.tableList];
    [SYRequestAPI sy_getClassServiceClassAttendList:parama success:^(id  _Nonnull responseObject) {
        if (self->pageIndex == 1) {
            [self->_dataArray removeAllObjects];
        }
        NSArray *array = [responseObject objectForKey:@"data"];
//        if (array.count>0) {
//            self->pageIndex ++;
//        }
        for (NSDictionary *dic in array) {
            BanJiKaoQingListModel *model = [BanJiKaoQingListModel yy_modelWithJSON:dic];
            [self->_dataArray addObject:model];
        }
        [self.tableList reloadData];
     //   NSLog(@"教学-班级-未上课时/已上课时-班级考勤 %@",responseObject);
        [MBProgressHUD mj_hideHUDForView:self.tableList];
        [self->_tableList.mj_header endRefreshing];
        [self->_tableList.mj_footer endRefreshing];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.tableList];
        [self->_tableList.mj_header endRefreshing];
        [self->_tableList.mj_footer endRefreshing];
         [self.tableList reloadData];
    }];
}
- (void)setKaiShiShiJian{
    self->_headerView.rightButton.bottomLabel.text = setDate()[0];
    endDate = setDate()[0];
    NSArray *array = [endDate componentsSeparatedByString:@"-"];
    self->jisshuNum = [self valueNum:array];
}
- (void)setJieShuShiJian{
    self->_headerView.leftButton.bottomLabel.text = setDate()[1];
    beginDate = setDate()[1];
    NSArray *array = [beginDate componentsSeparatedByString:@"-"];
    self->kaishiNum = [self valueNum:array];
}
NS_INLINE NSMutableArray *setDate(){
    NSMutableArray *data = [NSMutableArray new];
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    NSString *dateStr = [formatter stringFromDate:currentDate];
    NSInteger lastIndex = 0;
    NSDate *newdate;
    [data addObject:dateStr];
    [lastMonthComps setMonth:lastIndex-1];
    newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStrNext = [formatter stringFromDate:newdate];
    [data addObject:dateStrNext];
    return data;
}
@end
